/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:焦元义
 */

import React, {FC, useEffect, useMemo, useState,} from 'react';
import {Col, Input, Row, Tree,} from 'antd';
import services from '../dicCategory/service';
import DicPage from "./indexUnfold";
import {eachTree, filterTree, newDelay} from "@/utils/utils";
import config from "@/config";
import Permission from "@/components/Permission";

const {Search} = Input;
const delay = newDelay();

/** 系统字典模块 */
const SysDicPage: FC = () => {

  const [treeData, setTreeData] = useState();
  const [code, setCode] = useState();
  const [width, setWidth] = useState(3);
  const [expandedKeys, setExpandedKeys] = useState();
  const [aTreeData, setATreeData] = useState();


  useEffect(() => {
    //加载菜单树组件
    const getDicCategory = async () => {
      const data = await services.selectTreeList().then((r) => {
        return r.data
      });
      // setADate(data);
      // const treeData = translateTree(data);
      setATreeData(data);
      setTreeData(data);
    }
    getDicCategory();
  }, [])

  const onSelect = (selectedKeys: any, info: { node: any }) => {
    setCode(info.node);
  };

  const onExpand = (expandedKeys: any) => {
    setExpandedKeys(expandedKeys);
    return;
  };

  /** 筛选树*/
  const searchOnChange = (e: any) => {
    if (!aTreeData) return;
    const {value} = e.target;
    delay.run(() => {
      if (value && value.length > 0) {
        // console.log('value', value)
        const nodes = filterTree(aTreeData, current => (current.title as string).indexOf(value) > -1);
        setTreeData(nodes);
        const expandedKeys: string[] = [];
        eachTree(nodes, (current) => expandedKeys.push(current.key));
        setExpandedKeys(expandedKeys);
      } else {
        setTreeData(aTreeData);
        setExpandedKeys([]);
      }
    })
  };
  const tree = useMemo(() => {
    return (
      <div>
        {treeData && treeData.length ? (<Tree
          showIcon={true}
          height={650}
          draggable
          blockNode
          onSelect={onSelect}
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          treeData={treeData}
        />) : null}
      </div>
    );
  }, [treeData, expandedKeys]);

  const ChangeWidth = () => {
    const widths = width > 0 ? 0 : 3;
    setWidth(widths);

  }

  return (
    <Permission code={config.permission.sysDic.select}>
      <Row>
        <Col span={width}>
          <Search style={{marginBottom: 8}} placeholder="输入关键字" onChange={searchOnChange}/>
          {tree}
        </Col>
        <Col span={24 - width}>
          <DicPage selectCode={code} treeWidth={width} ChangeWidth={ChangeWidth}></DicPage>
        </Col>
      </Row>
    </Permission>
  );
};

export default SysDicPage;


